//
//  NoteViewController.swift
//  Keyboard
//
//  Created by xinglian on 2022/12/20.
//

import UIKit
class NoteViewController: BaseViewController {
    @IBOutlet var input: CCTextField!
    @IBOutlet var recordImg: UIImageView!
    @IBOutlet var recordTips: UILabel!
    @IBOutlet var addBtn: UIButton!
    var array = [NoteModel]()
    var sendNoteContent  = ""
    override func viewDidLoad() {
        super.viewDidLoad()
        self.initData()
    }
    
    deinit{
        NotificationCenter.default.removeObserver(self)
    }
    
    override func initUI() {
        let img = UIImageView(frame:CGRect(x:16, y:0, width:30, height:30))
        img.image = UIImage(named:"搜索")
        self.input.leftViewMode = .always
        self.input.leftView = img
        
        self.collectionView.register(NoteCell.nib(), forCellWithReuseIdentifier: NoteCell.ID())
        self.collectionView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(self.input.snp.bottom)
        }
        self.view.bringSubviewToFront(self.addBtn)
        self.view.bringSubviewToFront(self.recordTips)
        self.view.bringSubviewToFront(self.recordImg)
    }
    
   @objc func initData(){
        NoteTool.find { array in
            self.array = array
            self.collectionView.reloadData()
        }
    }
    @IBAction func actionForBtn(_ sender: UIButton) {
        let vc = NewNoteViewController()
        let model = NoteModel()
        model.stamp = NSDate.currentTimeStamp("yyyy-MM-dd HH:mm:ss")
        vc.model = model
        self.push(vc,true)
    }
}
//MARK: - 通知
extension NoteViewController{
    override func addNotify() {
        NotificationCenter.default.addObserver(self, selector: #selector(initData), name:updateNote, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(actionSendNote), name:BLE3610Response, object: nil)
    }
    
    @objc func actionSendNote(){
        if self.sendNoteContent != ""{
            BleDataTool.share.upload(0,self.sendNoteContent,false)
        }
        self.sendNoteContent = ""
    }
}
//MARK: - UITextField
extension NoteViewController:UITextFieldDelegate{
    func textFieldDidChangeSelection(_ textField: UITextField){
        if textField.markedTextRange == nil{
            NoteTool.search(textField.text ?? "") { array in
                self.array = array
                self.collectionView.reloadData()
            }
        }
    }
}

//MARK: - UICollectionViewDataSource
extension NoteViewController
{
    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        self.recordTips.isHidden = self.array.count > 0
        self.recordImg.isHidden = self.array.count > 0
        return  self.array.count
    }
    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier:NoteCell.ID(), for: indexPath) as! NoteCell
        cell.model = self.array[indexPath.row]
        return cell
    }
}

//MARK: - UICollectionViewDelegate
extension NoteViewController{
    override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let model = NoteModel.json(self.array[indexPath.row])
        self.sheet(LS("请选择"),LS("键盘只显示40个字节"),
                   [LS("删除记事本"),LS("查看记事本详情"),LS("记事本传到键盘")]){ [weak self](index,text) in
            switch text{
            case LS("删除记事本"):
                BleDataTool.share.delete("\((Int(model.stamp) ?? 0) - 946656000)")
                NoteTool.delete(model.title) {[weak self] in
                    self?.array.remove(at: indexPath.row)
                    self?.collectionView.reloadData()
                }
            case LS("查看记事本详情"):
                let vc = NewNoteViewController()
                vc.model = model
                self?.push(vc,true)
            case LS("记事本传到键盘"):
                if BLE.status != .connectedSucces{return CCHud.start(LS("请先连接设备"), stopTime: 1)}
                if model.title.count <= 0{ return CCHud.start(LS("标题不能为空"), stopTime: 1)}
                self?.sendNoteContent = model.content
                BleDataTool.share.upload(model.stamp.intValue(),model.title,true)
            default:
                break
            }
        }
        let vc = NewNoteViewController()
        vc.model = NoteModel.json(self.array[indexPath.row])
        self.push(vc,true)
    }
}
//MARK: - UICollectionViewDelegateFlowLayout
extension NoteViewController{
    
    override func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
    {
        let w = (self.view.bounds.size.width - 16 * 3) / 2
        return CGSize(width:w, height: w)
    }
    
    override func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat
    {
        return 16
    }
    
    override func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat
    {
        return 16
    }
    override func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets
    {
        return UIEdgeInsets(top:16, left:16, bottom: 16, right:16)
    }
}
